import React, {Component} from 'react';
import './index.less';
import {
    toast,
    promptBox,
    cacheTools
} from 'nc-lightapp-front';
import Pagination from 'src/hrpub/common/components/Pagination'

import QueryCenterAction from "./functions/QueryCenterAction";
import CenterLoadSubAction from "./functions/CenterLoadSubAction";
import updateButtonStatus from "../Header/functions/updateButtonStatus";

const tableId = 'psninfo';
const tableId2 = 'ctrtinfo';

const defaultPageInfo = {
    pageIndex: 1,
    pageSize: 10,
    total: 0,
    totalPage: 0
};

class RightTable extends Component {
    constructor(props) {
        super(props);
        this.state = {
            json: props.json,
            // 分页
            pageInfo: defaultPageInfo,

            tableHeight: '0px'
        };
    }

    componentWillReceiveProps(nextprops) {
        let nextjson = JSON.stringify(nextprops.json);
        let thisjson = JSON.stringify(this.props.json);
        if (nextjson !== thisjson) {
            this.setState({
                json: nextprops.json
            })
        }
        // 如果请求条件发生变化，则翻页组件初始化，重新请求数据
        let param = ['hrorgval', 'orgPk', 'deptPk', 'isOtherNode', 'inposFlag'];
        let queryFlag = param.every((key) => {
            return JSON.stringify(nextprops[key]) === JSON.stringify(this.props[key])
        }, this);
        if (!queryFlag) {
            this.reloadTable();
        }
    }

    componentDidMount() {
        this.onWindowResize();
        window.addEventListener('resize', this.onWindowResize);
    }

    /**
     * 检测屏幕高度变化，修改table高度
     */
    onWindowResize = () => {
        let tableHeight = (window.innerHeight - 190) / 2 + 'px';
        this.updateState({
            tableHeight
        })
    };

    /**
     * 更新state对象
     * @param data
     * @param callback
     */
    updateState(data, callback = () => {
    }) {
        this.setState(data, callback);
    }

    /**
     * 初始化翻页 重新请求人员数据
     * @param callback {function} 回调函数
     */
    reloadTable = (callback) => {
        let pageInfo = this.state.pageInfo;
        pageInfo.pageIndex = defaultPageInfo.pageIndex;
        this.setState({
            pageInfo
        }, () => {
            this.getPsnTable(callback)
        })
    };

    /**
     * 获取人员列表
     */
    getPsnTable(callback) {
        let {pageSize, pageIndex} = this.state.pageInfo;
        //清空表格
        this.emptyRightTable();
        let searchModalValue = {
            ...this.props.searchModalValue,
            //...this.props.search.getQueryInfo("psnquery", true)
        };
        QueryCenterAction(this.props.hrorgval, this.props.orgPk, this.props.deptPk, this.props.isOtherNode, searchModalValue, {
            pageIndex,
            pageSize: Number(pageSize)
        }, this.props.inposFlag).then(res => {
            if (callback && typeof callback === "function") {
                callback(res)
            }
            if (!res.data || !res.data[tableId]) return;
            //更新翻页组件
            this.updateState({
                pageInfo: res.data[tableId].pageInfo
            });
            let tableData = {rows: res.data[tableId].rows || []};
            // 更新列表数据
            this.props.editTable.setTableData(tableId, tableData);

            if (tableData.rows.length < 1) return;
            // 默认选中第一行数据
            this.props.editTable.focusRowByIndex(tableId, 0);
            this.onRowClick(this.props, tableId, tableData.rows[0]);
        })
    }

    /**
     * 清空表格
     */
    emptyRightTable() {
        this.props.updateState({
            pk_psndoc_sub: null
        });
        this.updateState({
            pageInfo: defaultPageInfo
        });
        this.props.editTable.setTableData(tableId, {rows: []});
        this.props.editTable.setTableData(tableId2, {rows: []});
    }

    /**
     * 获取合同列表
     */
    getContractTable(pk_psnjob) {
        //清空表格
        this.props.editTable.setTableData(tableId2, {rows: []});
        //清空已选择的合同主键
        this.props.updateState({
            pk_psndoc_sub: null
        }, () => {
            updateButtonStatus(this.props);
        });
        CenterLoadSubAction(this.props.hrorgval, pk_psnjob, true, this.props.searchModalValue).then(res => {
            if (!res.data || !res.data[tableId2]) return;
            this.props.editTable.setTableData(tableId2, res.data[tableId2])
        })
    }

    //每页显示条数
    pageSizeSelect = (val) => {
        this.state.pageInfo.pageSize = val;
        this.state.pageInfo.pageIndex = 1;
        this.updateState(this.state.pageInfo, () => {
            this.getPsnTable();
        });
    };
    //分页事件
    paginationEve = (key) => {
        this.state.pageInfo.pageIndex = key;
        this.updateState(this.state.pageInfo, () => {
            this.getPsnTable();
        });
    };

    onRowClick(props, moduleId, record) {
        let pk_psnjob = record.values.pk_psnjob.value;
        this.getContractTable(pk_psnjob)
    }

    onRowClick2(props, moduleId, record) {
        let pk_psndoc_sub = record.values.pk_psndoc_sub.value;
        this.props.updateState({
            pk_psndoc_sub
        }, () => {
            updateButtonStatus(this.props);
        })
    }

    /**
     * 点击合同编号
     */
    clickContractNum(record) {
        let pk_psndoc_sub = record.values.pk_psndoc_sub.value;
        // 签订=1,续签=2,变更=3,解除=4,终止=5
        let conttype = record.values.conttype.value + '';
        this.props.updateState({
            pk_psndoc_sub,
            conttype
        }, () => {
            this.props.showDetailPage();
        })
    }

    render() {
        const {editTable} = this.props;
        const {pageInfo} = this.state;
        let {createEditTable} = editTable;
        const pageParam = {
            current: ~~pageInfo.pageIndex,//当前页面, 从 1 开始计算，如果传入了这个props，则组件视为可控组件
            // defaultCurrent: pageInfo.pageIndex,// 默认当前页
            defaultPageSize: pageInfo.pageSize,// 默认每页条数
            hideOnSinglePage: false,// 只有一页时是否隐藏分页器
            pageSize: pageInfo.pageSize,// 每页条数
            pageSizeOptions: [10, 20, 30, 40, 50],// 指定每页显示多少条
            showQuickJumper: false,// 是否可以快速跳转至某页
            showSizeChanger: true,// 是否可以改变pageSize
            showTotal: '',// 函数 用于展示有多少条
            // size: pageInfo.,// 分页器尺寸
            total: pageInfo.total,// 数据总数
            onChange: this.paginationEve,// 页码改变回调函数
            onShowSizeChange: this.pageSizeSelect// pageSize改变的回调函数
        };
        return (
            <div className="right-table">
                <div className={'table-box table_print'}>
                    {
                        createEditTable(tableId, {
                            cancelCustomRightMenu: true,
                            showPagination: false, //是否展示分页
                            height: this.state.tableHeight,
                            showCheck: true,
                            onSelected: this.onRowClick.bind(this),
                            onRowClick: this.onRowClick.bind(this),
                            autoAffixScroll: false
                        })
                    }
                </div>
                <div className={'table-box'}>
                    {
                        createEditTable(tableId2, {
                            cancelCustomRightMenu: true,
                            showPagination: false, //是否展示分页
                            height: this.state.tableHeight,
                            showCheck: false,
                            onRowClick: this.onRowClick2.bind(this),
                            autoAffixScroll: false
                        })
                    }
                </div>
                <div className={'pagination'}>
                    <Pagination
                        {...pageParam}
                    />
                </div>
            </div>
        );
    }
}

export default RightTable;
